using System.Runtime.Remoting.Messaging;

namespace SDG.UnitTesting.Remoting
{
    public class SDGMessageSink : IMessageSink
    {
        private readonly string _exe;
        private readonly IMessageSink _nextSink;

        public SDGMessageSink(string exe, IMessageSink nextSink)
        {
            _exe = exe;
            _nextSink = nextSink;
        }

        #region IMessageSink Members

        public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
        {
            return NextSink.AsyncProcessMessage(msg, replySink);
        }

        public IMessageSink NextSink
        {
            get { return _nextSink; }
        }

        public IMessage SyncProcessMessage(IMessage msg)
        {
            IMethodCallMessage mcm = (msg as IMethodCallMessage);
            SDGExecute(mcm);
            return NextSink.SyncProcessMessage(msg);
        }


        #endregion

        private void SDGExecute(IMethodCallMessage mcm)
        {
            SDGExecuteAttribute[] attributes =
                mcm.MethodBase.GetCustomAttributes(typeof (SDGExecuteAttribute), true) as SDGExecuteAttribute[];

            if(attributes == null)
                return;

            foreach (SDGExecuteAttribute attribute in attributes)
            {
                attribute.Execute(_exe);
            }
        }
    }
}